package com.lagou.code.controller;

import com.lagou.code.entity.Code;
import com.lagou.code.mapper.CodeMapper;
import com.lagou.edu.service.EmailService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Random;

@RestController
@RequestMapping("/code")
public class CodeController {

    /*@Autowired
    private RestTemplate restTemplate;*/

    /*@Autowired
    private EmailFeignClient emailFeignClient;*/

    @Reference
    private EmailService emailService;

    @Autowired
    private CodeMapper codeMapper;


    private Random random = new Random();
    private StringBuffer sb = new StringBuffer();

    @GetMapping("/create/{email}")
    public boolean generateCodeAndSend(@PathVariable("email") String email) {
        sb.setLength(0);
        for (int i=0;i<6;i++) {
            sb.append(random.nextInt(10));
        }
        String code = sb.toString();
        codeMapper.add(email, code);
//        boolean result = emailFeignClient.sendCode2EmailAddr(email, code);
        boolean result = emailService.sendCode2EmailAddr(email, code);
        return result;
    }

    @GetMapping("/validate/{email}/{code}")
    public Integer validateCode(@PathVariable("email") String email, @PathVariable("code") String code) {
        Code codeEntity = codeMapper.findByEmail(email, code);
        if(codeEntity == null) {
            return 1;//错误
        } else if(codeEntity.getExpiretime().before(new Date())) {
            return 2;//超时
        } else {
            return 0;//正确
        }
    }
}
